package com.zhuj.codec;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhuj.core.Global;
import com.zhuj.core.entity.ClientRequest;
import com.zhuj.core.entity.ServerResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

/**
 * Created by Administrator on 2018/1/3.
 */
public class NrpcJsonDecode extends MessageToMessageDecoder<String>{

    private boolean sign;

    public NrpcJsonDecode(boolean sign){
        this.sign = sign;
    }

    protected void decode(ChannelHandlerContext channelHandlerContext, String s, List<Object> out) throws Exception {
        long a = System.currentTimeMillis();
        if (sign)
            out.add(clientDecode(s));
        else
            out.add(serverDecode(s));
        System.out.println("解码毫秒数："+(System.currentTimeMillis()-a));
    }

    private ServerResponse clientDecode(String s) throws ClassNotFoundException {
        JSONObject jsonObject = JSON.parseObject(s);
        ServerResponse response = new ServerResponse();
        response.setResponseId(jsonObject.getInteger("responseId"));
        String error = jsonObject.getString("error");
        if (error == null){
            response.setType(classParse(jsonObject.getString("type")));
            response.setResult(JSON.parseObject(jsonObject.getString("result"),response.getType()));
        }else {
            response.setError(error);
        }
        return response;
    }

    private ClientRequest serverDecode(String s) throws ClassNotFoundException {
        JSONObject jsonObject = JSON.parseObject(s);
        ClientRequest request = new ClientRequest();
        request.setRequestId(jsonObject.getInteger("requestId"));
        request.setService(jsonObject.getString("service"));
        request.setMethod(jsonObject.getString("method"));
        JSONArray ptArray = jsonObject.getJSONArray("paramTypes");
        JSONArray pArray = jsonObject.getJSONArray("params");
        Class[] pts = new Class[ptArray.size()];
        Object[] ps = new Object[ptArray.size()];
        for (int i=0;i<pts.length;i++){
            if (i < pArray.size()){
                pts[i] = classParse(ptArray.getString(i));
                ps[i] = JSON.parseObject(pArray.getString(i),pts[i]);
            }else {
                pts[i] = classParse(ptArray.getString(i));
                ps[i] = null;
            }
        }
        request.setParamTypes(pts);
        request.setParams(ps);
        return request;
    }

    private Class classParse(String className) throws ClassNotFoundException {
        Class clazz = Global.BasicType.getType(className);
        if (clazz == null){
            clazz = Class.forName(className);
        }
        return clazz;
    }
}
